//
//  FourView.m
//  YDD
//
//  Created by 欧洪飞 on 2017/8/22.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "FourView.h"
#import "ImageAndTextTableViewCell.h"
#import "TZImagePickerController.h"

@interface FourView ()<UITableViewDataSource,UITableViewDelegate,TZImagePickerControllerDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *imageAndTextTable;

@property (weak, nonatomic) IBOutlet UIButton *addImageButton;

@property (nonatomic, strong) NSMutableArray *dataImageArray;

@property (nonatomic, strong) UIAlertController *sheet;

@property (nonatomic, assign) NSInteger selRow;

- (IBAction)addImageEvent:(UIButton *)sender;

@end

@implementation FourView


 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }



- (void)layoutSubviews{
    [super layoutSubviews];
    self.imageAndTextTable.delegate = self;
    self.imageAndTextTable.dataSource = self;
    self.imageAndTextTable.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.imageAndTextTable setBackgroundColor:[UIColor clearColor]];
    [self.imageAndTextTable registerNib:[UINib nibWithNibName:@"ImageAndTextTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Cell"];
    [self addSubview:self.imageAndTextTable];
    
    CAShapeLayer *border = [CAShapeLayer layer];
    // 线条颜色
    border.strokeColor = HexColorInt32_t(4A8AFF).CGColor;
    border.fillColor = nil;
    border.path = [UIBezierPath bezierPathWithRect:self.addImageButton.bounds].CGPath;
    border.frame = self.addImageButton.bounds;
    // 不要设太大 不然看不出效果
    border.lineWidth = 1;
    border.lineCap = @"square";
    // 第一个是 线条长度 第二个是间距 nil时为实线
    border.lineDashPattern = @[@4, @4];
    [self.addImageButton.layer addSublayer:border];
    
    self.sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        BOOL ishave = [self doesCameraSupportTakingPhotos];
        if (ishave == YES) {
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.delegate = self;
            [[self getCurrentVC] presentViewController:picker animated:YES completion:nil];
        }else{
            [LICGToast showWithText:@"相机不可用" bottomOffset:20 duration:5];
        }
    }];
    
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        BOOL ishave = [self isPhotoLibraryAvailable];
        if (ishave == YES) {
            TZImagePickerController *imagePC=[[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
            [imagePC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *imagarr, NSArray *array, BOOL bl) {
                UIImage *selimage = [imagarr firstObject];
                [self uploadImage:selimage];
                
            }];
            [[self getCurrentVC] presentViewController:imagePC animated:YES completion:nil];
        }else{
            [LICGToast showWithText:@"相册不可用" bottomOffset:20 duration:5];
        }
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [self.sheet addAction:cancelAction];
    [self.sheet addAction:cameraAction];
    [self.sheet addAction:albumAction];
}

#pragma mark ====UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [self uploadImage:image];
    [[self getCurrentVC] dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImage:(UIImage *)image{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:@"pic.png" forKey:@"pic"];
    [parmas setObject:@"name" forKey:@"name"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@/App/Norm/upload",urlHead];
    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:data name:@"pic" fileName:fileName mimeType:@"image/png"];
        [formData appendPartWithFileData:data name:@"name" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *op = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSLog(@"dic:%@",op);
        NSInteger error =[[op objectForKey:@"error"] integerValue];
        if (error == 200) {
            NSString *imageString = [op objectForKey:@"result"];
            NSLog(@"imgUrl1:%@",imageString);
            if (self.dataImageArray.count > 0){
                NSMutableDictionary *itemdic = [self.dataImageArray objectAtIndex:self.selRow];
                if ([itemdic isKindOfClass:[NSDictionary class]]) {
                    [itemdic setValue:imageString forKey:@"picimga"];
                }else{
                    NSMutableDictionary *itemdic = [[NSMutableDictionary alloc]init];
                    [itemdic setValue:imageString forKey:@"picimga"];
                    [self.dataImageArray replaceObjectAtIndex:self.selRow withObject:itemdic];
                }
            }else{
                NSMutableDictionary *itemdic = [[NSMutableDictionary alloc]init];
                [itemdic setValue:imageString forKey:@"picimga"];
                [self.dataImageArray addObject:itemdic];
                
            }
            [self.imageAndTextTable reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)setFourData:(NSArray *)array{
    self.dataImageArray = [array mutableCopy];
    [self.imageAndTextTable reloadData];
    self.updateHeightAction(self.dataImageArray.count);
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.dataImageArray.count > 0) {
        return self.dataImageArray.count;
    }else{
        return 1;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 323.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    ImageAndTextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ImageAndTextTableViewCell" owner:nil options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.dataImageArray.count > 0) {
        NSMutableDictionary *itemdic = [self.dataImageArray objectAtIndex:indexPath.row];
        if ([itemdic isKindOfClass:[NSDictionary class]]) {
            NSString *itemImageString =  [itemdic objectForKey:@"picimga"];
            NSString *itemTitleString = [itemdic objectForKey:@"instructiona"];
            if (itemImageString.length > 0) {
                NSString *imageUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],itemImageString];
                [cell.imageButton sd_setBackgroundImageWithURL:[NSURL URLWithString:imageUrl] forState:UIControlStateNormal];
                [cell.imageButton setTitle:nil forState:UIControlStateNormal];
                [cell.imageButton setImage:nil forState:UIControlStateNormal];
            }else{
                [cell.imageButton setTitle:@"上传照片" forState:UIControlStateNormal];
                [cell.imageButton setImage:[UIImage imageNamed:@"图片"] forState:UIControlStateNormal];
            }
            if (itemTitleString.length > 0) {
                [cell.valueText setText:itemTitleString];
            }
        }else{
            [cell.imageButton setTitle:@"上传照片" forState:UIControlStateNormal];
            [cell.imageButton setImage:[UIImage imageNamed:@"图片"] forState:UIControlStateNormal];
        }
    }else{
        [cell.imageButton setTitle:@"上传照片" forState:UIControlStateNormal];
        [cell.imageButton setImage:[UIImage imageNamed:@"图片"] forState:UIControlStateNormal];
        
    }
    
    cell.addImageActionButton = ^(UIButton *sender) {
        self.selRow = indexPath.row;
        [[self getCurrentVC] presentViewController:self.sheet animated:YES completion:nil];
    };
    cell.deleteImageActionButton = ^(UIButton *sender) {
        if (self.dataImageArray.count > 0) {
            [self.dataImageArray removeObjectAtIndex:indexPath.row];
            [self.imageAndTextTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        
    };
    cell.textChangeActionButton = ^(UITextView *textview) {
        if (self.dataImageArray.count > 0) {
            NSDictionary *edititemdic = [self.dataImageArray objectAtIndex:indexPath.row];
            NSMutableDictionary *editEditDic = [edititemdic mutableCopy];
            if ([edititemdic isKindOfClass:[NSDictionary class]]){
                [editEditDic setValue:textview.text forKey:@"instructiona"];
                [self.dataImageArray replaceObjectAtIndex:indexPath.row withObject:editEditDic];
            }else{
                NSMutableDictionary *addDic = [[NSMutableDictionary alloc]init];
                [addDic setValue:textview.text forKey:@"instructiona"];
                [self.dataImageArray replaceObjectAtIndex:indexPath.row withObject:addDic];
            }
        }else{
            NSMutableDictionary *addDic = [[NSMutableDictionary alloc]init];
            [addDic setValue:textview.text forKey:@"instructiona"];
            [self.dataImageArray addObject:addDic];
        }
        
    };
    return cell;
}



- (IBAction)addImageEvent:(UIButton *)sender {
    if (self.dataImageArray.count >=4) {
        [LICGToast showWithText:@"最多添加4组图文说明"];
        return;
    }
    
    [self.dataImageArray addObject:@"kong"];
    [self.imageAndTextTable reloadData];
    self.updateHeightAction(self.dataImageArray.count);
}

- (NSMutableArray *)dataImageArray{
    if (!_dataImageArray) {
        _dataImageArray = [[NSMutableArray alloc]init];
    }
    return _dataImageArray;
}

// 检查摄像头是否支持拍照

- (BOOL)doesCameraSupportTakingPhotos{
    
    return [self cameraSupportsMedia:(NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
    
}
// 判断是否支持某种多媒体类型：拍照，视频

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    
    __block BOOL result = NO;
    
    if ([paramMediaType length] == 0){
        
        NSLog(@"Media type is empty.");
        
        return NO;
        
    }
    
    NSArray *availableMediaTypes =[UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    
    [availableMediaTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL*stop) {
        
        NSString *mediaType = (NSString *)obj;
        
        if ([mediaType isEqualToString:paramMediaType]){
            
            result = YES;
            
            *stop= YES;
            
        }
    }];
    
    return result;
    
}

#pragma mark - 相册文件选取相关

// 相册是否可用

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
    
}

- (UIViewController *)getCurrentVC {
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    id nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    // 如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        NSLog(@"===%@",[window subviews]);
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
    }
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        // UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    return result;
}

- (NSString *)getImageAndTitleDataArray{
    NSString *returnString = @"";
    if (self.dataImageArray.count > 0) {
        NSMutableArray *retArray = [[NSMutableArray alloc]init];
        for (NSDictionary *item in self.dataImageArray) {
            if ([item isKindOfClass:[NSDictionary class]]) {
                [retArray addObject:item];
            }
        }
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:retArray options:kNilOptions error:&error];
        returnString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return returnString;
}

@end
